#coding: utf-8
import subprocess
import simplejson as json
from django.http import HttpResponse
from functools import wraps
from django.utils.decorators import available_attrs

from main.utils import exec_command

ROCKS_URL = "http://music.tmradio.net/api/track/rocks.json"
SUCKS_URL = "http://music.tmradio.net/api/track/sucks.json"
AUTH_URL = "http://music.tmradio.net/api/auth.json"
QUEUE_URL = "http://music.tmradio.net/track/queue.json?track={track_id}&token={token}"

def tm_request(data, url, method = 'POST', decode_json = True):
    command = "curl -X {method} -d '{data}' '{url}'".format(data=data, url=url, method=method)
    response = exec_command(command)
    if not decode_json: return response
    try:
        return json.loads(response)
    except json.JSONDecodeError:
        return response
    return None

def tm_get_request(url, decode_json = True):
    command = "curl '{url}'".format(url=url)
    response = exec_command(command)
    if not decode_json: return response
    try:
        return json.loads(response)
    except json.JSONDecodeError:
        return response
    return None

def send_rocks(token, track_id):
    return tm_request("token={0}&track_id={1}".format(token, track_id), ROCKS_URL)

def send_sucks(token, track_id):
    return tm_request("token={0}&track_id={1}".format(token, track_id), SUCKS_URL)

def send_queue_track(token, track_id):
    return tm_get_request( QUEUE_URL.format(track_id = track_id, token = token), decode_json = False )

def request_token(user_aid, aid_type):
    return tm_request('id={0}&type={1}'.format(user_aid, aid_type), AUTH_URL)

def tm_token_required(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapped(request, *args, **kwargs):
        profile = kwargs.get('profile', None)
        if not profile or not profile.tm_token: 
            return tm_json_response(status='error', message=u'Нет токена. Получить токен можно на странице профиля.')
        return func(request, *args, **kwargs)
    return wrapped

def tm_json_response(**kwargs):
    return HttpResponse(json.dumps(kwargs))